import { Component, Prop, Vue } from 'vue-property-decorator';
import style from '@/styles/components/window.module.less';

@Component({})
export default class Window extends Vue {
  @Prop({ type: Number }) private value!: 0;
  @Prop({ type: Boolean }) private disabled!: false;

  private lastPageX = -1;
  private xDistance = 0;

  private get _value() {
    if (this.value < 0) {
      return 0;
    } else if (this.value > 100) {
      return 100;
    }
    return this.value;
  }

  public render() {
    return (
      <div class={[style['window'], this.disabled && style['window-disabled']]}>
        <div
          class={style['window-right']}
          style={{ right: `${this._value / 2}%` }}
          on={{
            touchstart: this.handleTouchStart,
            touchmove: this.handleTouchMove,
            touchend: this.handleTouchEnd
          }}></div>
        <div
          class={style['window-border']}></div>
      </div>
    );
  }

  private handleTouchStart(e: TouchEvent) {
    if (e.targetTouches.length > 1 || this.disabled) {
      return;
    }
    this.lastPageX = e.targetTouches[0].pageX;
  }

  private handleTouchMove(e: TouchEvent) {
    if (e.targetTouches.length > 1 || this.lastPageX < 0 || this.disabled) {
      return;
    }
    this.xDistance = e.targetTouches[0].pageX - this.lastPageX;
  }

  private handleTouchEnd(e: TouchEvent) {
    if (e.targetTouches.length > 1 || this.lastPageX < 0 || this.disabled) {
      return;
    }
    if (this.xDistance > 0) {
      // 右滑
      this.$emit('slide', 'left');
    } else if (this.xDistance < 0) {
      // 左滑
      this.$emit('slide', 'right');
    } else {
      this.$emit('slide', 'OFF');
    }
    this.lastPageX = -1;
    this.xDistance = 0;
  }
}
